import models.MyConfig;
import models.ReadProperties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Properties;

/**
 * Created by yangxianming on 2017/9/15.
 * 处理文件上传
 */
@WebServlet(name = "uploadFile", urlPatterns = {"/uploadFile"}, loadOnStartup = 2)
@MultipartConfig
public class UploadFile extends HttpServlet {
    MyConfig myConfig = new MyConfig();
    Properties properties;

    @Override
    public void init(ServletConfig config) throws ServletException {
        ReadProperties readProperties = new ReadProperties(config.getServletContext().getRealPath("/"));
        myConfig.setPropertiesConfig(readProperties);
        myConfig.setAppPath(config.getServletContext().getRealPath("/"));
        this.properties = readProperties.getProperties();
        myConfig.setSplitMark();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String projectName = request.getParameter("projectName");
        //获取系统名字
        String splitMark = myConfig.getSplitMark("splitMark");
        String savePath = myConfig.getAppPath() + splitMark + "jmeterScript" + splitMark;
//        String savePath = jmeterScriptDir + projectName + splitMark;

        //获取上传的文件集合
        Collection<Part> parts = request.getParts();
        //上传单个文件
        if (parts.size()==1) {
            //Servlet3.0将multipart/form-data的POST请求封装成Part，通过Part对上传的文件进行操作。
            //Part part = parts[0];//从上传的文件集合中获取Part对象
            Part part = request.getPart("file");//通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
            //Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
            //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
            String header = part.getHeader("content-disposition");
            //获取文件名
            String fileName = getFileName(header);
            System.out.println("FILENAME:" + fileName);
            //把文件写到指定路径
            part.write(savePath + fileName);
        }else {
            //一次性上传多个文件
            for (Part part : parts) {//循环处理上传的文件
                //获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
                String header = part.getHeader("content-disposition");
                //获取文件名
                String fileName = getFileName(header);
                //把文件写到指定路径
                part.write(savePath + fileName);
            }
        }
        PrintWriter out = response.getWriter();
        out.println("ok");
        out.flush();
        out.close();

    }

    private String getFileName(String header) {
        /**
         * String[] tempArr1 = header.split(";");代码执行完之后，在不同的浏览器下，tempArr1数组里面的内容稍有区别
         * 火狐或者google浏览器下：tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
         * IE浏览器下：tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
         */
        String[] tempArr1 = header.split(";");
        /**
         *火狐或者google浏览器下：tempArr2={filename,"snmp4j--api.zip"}
         *IE浏览器下：tempArr2={filename,"E:\snmp4j--api.zip"}
         */
        String[] tempArr2 = tempArr1[2].split("=");
        //获取文件名，兼容各种浏览器的写法
        return tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", "");
    }
}
